#!/usr/bin/env python3.9
# -*- encoding: utf-8 -*-
"""
@文件        :services.py
@说明        : 订单服务类
@时间        :2022/12/23 17:24:33
@作者        :Mars
@版本        :1.0
"""
import datetime

import numpy as np
import pandas as pd
from django.db.models import Count, Sum

from mars.apps.oauth.models import OAuthMPUser

from .models import Order


class OrderService:
    @staticmethod
    def get_analysis_data(periods=31):
        # 最近订单
        orders = Order.objects.filter(status=1).order_by("-create_time")[:20]
        # 订单总数
        orders_total = Order.objects.filter(status=1).aggregate(
            orders_total=Count("order_no")
        )["orders_total"]
        # 今日新增订单
        orders_today = Order.objects.filter(
            status=1, create_time__gt=datetime.date.today()
        ).aggregate(orders_cnt=Count("order_no"))["orders_cnt"]
        # 用户总数
        users_total = OAuthMPUser.objects.aggregate(users_total=Count("openid"))[
            "users_total"
        ]
        # 今日新增用户数
        users_today = OAuthMPUser.objects.filter(
            create_time__gt=datetime.date.today()
        ).aggregate(users_total=Count("openid"))["users_total"]

        # 创建日期索引
        df_index = pd.date_range(end=datetime.date.today(), periods=periods)

        # 按日期汇总
        orders_by_date = (
            Order.objects.extra(
                select={"create_time": "DATE_FORMAT(create_time,'%%Y-%%m-%%d')"}
            )
            .filter(status=1, create_time__gt=df_index[0])
            .values("func_name", "create_time")
            .annotate(sum_money=Sum("total"))
        )
        # 按日期索引初始换df
        df = pd.DataFrame(
            np.zeros((periods, 5)),
            index=df_index,
            columns=[
                "证件照",
                "更改背景",
                "裁剪照片",
                "压缩照片",
                "风格化照片",
            ],
        )
        # 向df中赋值，某天某功能的总收入
        for item in orders_by_date:
            df.loc[
                item["create_time"],
                item["func_name"],
            ] = float(item["sum_money"])
        # 获取df的日期索引作为labels
        chart_labels = df_index.map(
            lambda x: x.to_pydatetime().strftime("%Y-%m-%d")
        ).tolist()

        # 按功能项汇总数量
        orders_by_func = (
            Order.objects.filter(status=1, create_time__gt=df_index[0])
            .values("func_name")
            .annotate(cnt=Count("id"))
        )
        func_cnt = {}
        func_total = 0
        # 遍历结果集，重新组织数据
        for func in orders_by_func:
            func_cnt[func["func_name"]] = func["cnt"]
            func_total = func_total + func["cnt"]

        # 格式化输出值
        data = {
            "orders_total": orders_total,
            "orders_today": orders_today,
            "users_total": users_total,
            "users_today": users_today,
            "chart_title": "{}-{}".format(
                df_index[0].strftime("%Y年%m月%d日"), df_index[-1].strftime("%Y年%m月%d日")
            ),
            "chart_labels": chart_labels,
            "make_idphoto": df["证件照"].tolist(),
            "change_bg": df["更改背景"].tolist(),
            "clip_photo": df["裁剪照片"].tolist(),
            "compress_photo": df["压缩照片"].tolist(),
            "human_style": df["风格化照片"].tolist(),
            "make_idphoto_cnt": func_cnt.get("证件照" , 0),
            "change_bg_cnt": func_cnt.get("更改背景" , 0),
            "clip_photo_cnt": func_cnt.get("裁剪照片" , 0),
            "compress_photo_cnt": func_cnt.get("压缩照片" , 0),
            "human_style_cnt": func_cnt.get("风格化照片" , 0),
            "func_total": func_total,
            "orders": orders,
        }
        return data
